package com.hunantv.mglive.ui.live;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.ChatDataModel;
import com.hunantv.mglive.data.GiftDataModel;
import com.hunantv.mglive.data.GiftNumModel;
import com.hunantv.mglive.data.GiftShowViewDataModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.data.login.UserInfoData;
import com.hunantv.mglive.mqtt.data.MqttLastMsgData;
import com.hunantv.mglive.mqtt.data.MqttResponseData;
import com.hunantv.mglive.ui.adapter.ChatListAdapter;
import com.hunantv.mglive.ui.entertainer.data.ContributionInfoData;
import com.hunantv.mglive.utils.GiftUtil;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.MGLiveMoneyUtil;
import com.hunantv.mglive.utils.MessageUtil;
import com.hunantv.mglive.utils.MqttChatUtils;
import com.hunantv.mglive.utils.RoleUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.GiftShowView;
import com.hunantv.mglive.widget.LiveRemindDialog;
import com.hunantv.mglive.widget.StarMsgView;
import com.hunantv.mglive.widget.Toast.ConfirmDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link BaseFragment} subclass.
 */
public class ChatFragment extends BaseFragment implements MqttChatUtils.MqttCallback, MessageUtil.iNotifyMsgListCallBack{
    private String TAG = "JUNE";
    boolean isShowChatInputView = false;
    public static final String TYPE_LIVE = "liveshow";
    public static final String TYPE_BACK = "tp_1";
    public static final String TYPE_VIDEO_OFF = "tp_2";
    private static final int CHAT_NNOTIFY = 1;
    private static final int CHAT_SEND_MSG = 2;
    private static final int CHAT_UPDATE_HOT_VALUE = 3;
    private static final int CHAT_SEND_GIFT = 4;
    private static final int CHAT_STAR_MSG = 5;
    private static final int CHAT_LAST_MSG = 6;
    private static final int LIVE_OPEN_MSG = 9;

    //底部
    private RelativeLayout bottomLayout;
    //聊天View
    private RelativeLayout inputChatLayout;
    //聊天输入框
    private EditText inputChatText;
    private TextView sendChatBtn;
    //喊话滑块
    private View mShoutSwitch;
    private ImageView mShoutImg;
    //是否喊话
    private boolean isYell = false;
    private String mTitle;
    private View mEptZone;
    private ImageView mGiftIcon;
    private ImageView flowerImg;//送花
    private TextView flowerTxt;//送花
    //聊天区域
    private ListView mChatListView;
    private StarMsgView mStarMsgView;
    private ChatData chatTmp;

    private ChatListAdapter mChatListAdapter;
    private GiftDataModel mYellGifData;
    //空白数据，用来填充聊天区域最下部分
    private List<ChatDataModel> mChatList = Collections.synchronizedList(new ArrayList<ChatDataModel>());
    //礼物指示器列表
    private StarLiveDetailCentreFragment mCentreFragment;
    private FrameLayout mMsgReminder;//聊天室的新消息提醒
    private GiftAnimData giftAnimData = null;//送礼动画

    private MessageUtil mMessageUtil;
    private GiftShowView mGiftShowView;

    /**
     * 快捷礼物的数据
     */
    private GiftDataModel mShortCutGiftData;

    private ChatViewCallback mChatViewCallback;

    private ContributionInfoData mContributionInfo;

    private ConfirmDialog mConfirmDialog;

    private List<StarModel> mStarList;
    private StarModel mStarInfo;

    private String mFlag, mKey;
    private boolean mIsOpenConnectionMqtt = false;

    private RelativeLayout mGifyShowView;
    private RelativeLayout mAnimOtherView;
    /**
     * VideoFragmnet 通信接口
     */
    private Handler mHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case CHAT_NNOTIFY:
                    if (msg.obj != null) {
                        ChatDataModel chatModle = (ChatDataModel) msg.obj;
                        mMessageUtil.addMsg(chatModle);
                    }
                    break;
                case CHAT_SEND_MSG:
                    if (msg.obj != null) {
                        ChatData chatData = (ChatData) msg.obj;
                        if (mChatViewCallback != null) {
                            mChatViewCallback.hasMsg(chatData);
                        }
                    }
                    break;
                case CHAT_UPDATE_HOT_VALUE:
                    if (msg.obj != null) {
                        ChatData chatData = (ChatData) msg.obj;
                        updateHotValue(chatData);
                    }
                    break;
                case CHAT_STAR_MSG:
                    if (msg.obj != null) {
                        ChatDataModel chatModle = (ChatDataModel) msg.obj;
                        if (mStarInfo != null && mStarInfo.getUid().equals(chatModle.uuid) && mStarMsgView != null) {
                            mStarMsgView.display(chatModle.content);
                        }
                    }
                    break;
                case CHAT_SEND_GIFT:
                    if (msg.obj != null) {
                        GiftShowViewDataModel dataModel = (GiftShowViewDataModel) msg.obj;
                        mGiftShowView.show(dataModel);
                    }
                    break;
                case CHAT_LAST_MSG:
                    if (msg.obj != null) {
                        List<ChatDataModel> chatList = (List<ChatDataModel>) msg.obj;
                        mChatList.addAll(chatList);
                        mChatListAdapter.notifyDataSetChanged();
                    }
                    break;
                case LIVE_OPEN_MSG:
                    showLiveMessageDialog();
                    break;
                default:
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_chat_fragmenrt, container, false);
        mAnimOtherView = (RelativeLayout) view.findViewById(R.id.rl_anim_other_view);
        mMsgReminder = (FrameLayout) view.findViewById(R.id.ll_chat_msg_remider_view);
        mMsgReminder.setVisibility(View.GONE);
        mMsgReminder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setVisibility(View.GONE);
                if (null != mChatListView) {
                    mChatListView.setSelection(mChatListView.getBottom());
                }
            }
        });
        mGifyShowView = (RelativeLayout) view.findViewById(R.id.rl_chat_gift_show_view);
        mGiftShowView = new GiftShowView(getContext(), mGifyShowView, false);
        mMessageUtil = new MessageUtil(mChatList, this);
        //聊天ListView
        mChatListView = (ListView) view.findViewById(R.id.lv_chat_list);
        View mVStarMsg = view.findViewById(R.id.layout_star_msg);
        mChatListAdapter = new ChatListAdapter(mChatList, getContext());
        mChatListView.setAdapter(mChatListAdapter);
        mChatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ChatDataModel data = mChatListAdapter.getItem(position);
                if (null != data && !StringUtil.isNullorEmpty(data.name1)) {
                    if (!isShowChatInputView) {
                        changeChatInput();
                    }
                    if (null != inputChatText) {
                        inputChatText.setText("@" + data.name1 + " ");
                        inputChatText.setSelection(inputChatText.getText().length());
                    }
                }
            }
        });
        mChatListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                            if (null != mMsgReminder && mMsgReminder.getVisibility() == View.VISIBLE) {
                                mMsgReminder.setVisibility(View.GONE);
                            }
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        mCentreFragment = (StarLiveDetailCentreFragment) getChildFragmentManager().findFragmentById(R.id.fragmenrt_live_centre);
        RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) mChatListView.getLayoutParams();
        //按比例缩放直播窗体
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
        ps.topMargin = ps.topMargin + (int) (width * 0.75);
        mChatListView.setLayoutParams(ps);
        ps = (RelativeLayout.LayoutParams) mGifyShowView.getLayoutParams();
        ps.topMargin = ps.topMargin + (int) (width * 0.75);
        mGifyShowView.setLayoutParams(ps);
        ps = (RelativeLayout.LayoutParams) mVStarMsg.getLayoutParams();
        ps.topMargin = ps.topMargin + (int) (width * 0.75);
        mVStarMsg.setLayoutParams(ps);
        mStarMsgView = new StarMsgView(getActivity(), mVStarMsg);

        initChatView(view);
        initBottomView(view);
        initDialog();
        loadChatData();
        return view;
    }

    /**
     * 初始化聊天区域
     */
    private void initChatView(View view) {
        //聊天输入View
        inputChatLayout = (RelativeLayout) view.findViewById(R.id.rl_chat_inputChatLayout);
        //聊天输入框
        inputChatText = (EditText) view.findViewById(R.id.edt_inputChatText);
        inputChatText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER){
                    sendChat();
                }
                return false;
            }
        });
        //发送按钮
        sendChatBtn = (TextView) view.findViewById(R.id.tv_chat_sendChatBtn);
        sendChatBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendChat();
            }
        });
        //sendChatBtn.setEnabled(false);//maxxiang  这里为什么要enable false啊，
        //喊话滑块
        mShoutSwitch =  view.findViewById(R.id.fl_chat_shout);
        mShoutImg = (ImageView) view.findViewById(R.id.iv_chat_shout);
        //聊天喊话滑块
        mShoutSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }
                if (mYellGifData == null)
                    return;
                if (isYell) {
                    inputChatText.setHint(getString(R.string.star_live_input_msg));
                    mShoutImg.setSelected(false);
                    isYell = false;
                } else {
                    if (mContributionInfo != null && !ContributionInfoData.GRADE_LEVEL_NO.equals(mContributionInfo.getGradeName())) {
                        inputChatText.setHint(getString(R.string.live_send_msg_vip));
                    } else {
                        inputChatText.setHint(getString(R.string.live_send_msg, mYellGifData.getPrice() + ""));
                    }
                    mShoutImg.setSelected(true);
                    isYell = true;
                }
            }
        });
    }

    private void sendChat(){
        if (getMqttClientId() != null) {
            String chatText = inputChatText.getText().toString();
            inputChatText.setText("");
            if (!StringUtil.isNullorEmpty(chatText)) {
                if (isYell) {
                    if (mYellGifData != null) {
                        sendGrund(chatText, mYellGifData);
                    }
                } else {
                    sendChatContent(chatText);
                }
            }
        }
        isShowChatInputView = true;
        changeChatInput();
    }

    /**
     * 初始化底部的三个功能按钮
     *
     * @param view view
     */
    private void initBottomView(View view) {
        //底部区域
        bottomLayout = (RelativeLayout) view.findViewById(R.id.ll_chat_bottomLayout);//底部按钮布局
        LinearLayout llChatBtn = (LinearLayout) view.findViewById(R.id.ll_chat);
        LinearLayout llFlower = (LinearLayout) view.findViewById(R.id.ll_flower);

        flowerImg = (ImageView) llFlower.findViewById(R.id.ll_flower_img);
        flowerTxt = (TextView) llFlower.findViewById(R.id.ll_flower_txt);

        updateShortCutGiftView();

        //显示聊天窗
        llChatBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }
                if (!isLogin()) {
                    jumpToLogin("登录以后才可以聊天哦~");
                    return;
                }
                isShowChatInputView = false;
                changeChatInput();
            }
        });
        llFlower.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }
                if (!isLogin()) {
                    jumpToLogin("登录以后才可以赠送礼物哦~");
                } else {
                    if (null != mShortCutGiftData) {
                        ImageView view = (ImageView) v.findViewById(R.id.ll_flower_img);
                        setAnimData(mShortCutGiftData, view);
                        sendChatFlower();
                    }
                }
            }
        });
        mGiftIcon = (ImageView) view.findViewById(R.id.iv_chat_giftIcon);//礼物
        //显示礼物窗口
        mGiftIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin()) {
                    jumpToLogin("登录以后才可以赠送礼物哦~");
                    return;
                }
                if (mChatViewCallback != null) {
                    mChatViewCallback.changeGiftView(true);
                    mEptZone.setVisibility(View.VISIBLE);
                }
            }
        });


        bottomLayout.setVisibility(View.VISIBLE);
        mEptZone = view.findViewById(R.id.ct_full_touch_pad);
        mEptZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInput();
                mEptZone.setVisibility(View.GONE);
            }
        });
    }

    private void initDialog() {
        mConfirmDialog = new ConfirmDialog(getContext(), R.string.tips_not_gold, R.string.ok_1, R.string.cancel);
        mConfirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                MGLiveMoneyUtil.getInstance().goMGLiveMonneyPay(getActivity());
                mConfirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                mConfirmDialog.cancel();
            }
        });
    }

    private void hideInput() {
        if (isShowChatInputView) {
            changeChatInput();
        }
        if (mChatViewCallback != null) {
            mChatViewCallback.changeGiftView(false);
        }
    }

    /**
     * 更新底部送花(快捷礼物)的显示
     */
    private void updateShortCutGiftView() {
        if (null != mShortCutGiftData) {
            if (null != flowerImg) {
                Glide.with(this).load(mShortCutGiftData.getPhoto()).into(flowerImg);
            }
            if (null != flowerTxt) {
                flowerTxt.setText(mShortCutGiftData.getName());
            }
        }
    }

    private void updateSendChatEditTextView() {
        if (mYellGifData != null) {
            inputChatText.setHint(getString(R.string.star_live_input_msg));
        }
    }

    private void setAnimData(GiftDataModel giftData, ImageView iv) {
        if (giftData == null || iv == null)
            return;

        int[] location = new int[2];
        iv.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
        giftAnimData = new GiftAnimData();
        giftAnimData.photo = giftData.getPhoto();
        giftAnimData.hots = giftData.getHots();
        giftAnimData.formX = location[0] + iv.getMeasuredWidth() / 6;
        giftAnimData.formY = location[1] - iv.getMeasuredHeight() / 2;
    }


    public void setData(String flag, String key) {
        this.mFlag = flag;
        this.mKey = key;
        getMqtt().startMqttService(flag, key, this);
        mChatList.clear();
        mChatListAdapter.notifyDataSetChanged();
        hideInput();
        getLastMsg();
    }

    /**
     * 设置艺人信息对象并更新艺人信息界面
     *
     * @param mStarInfo mStarInfo
     */
    public void setStarInfo(StarModel mStarInfo) {
        this.mStarInfo = mStarInfo;
        mLiveReindDialog = null;//切换用户要重新初始化直播提示框
        loadContrInfo();
        sendGuardMessage();

        getIsLiveOpen();//查看当前查看的用户是否在直播

        if (null != mCentreFragment) {
            mCentreFragment.setStarInfo(getStarInfo());
        }
        if (mStarInfo != null) {
            mStarMsgView.initView(mStarInfo.getPhoto(), mStarInfo.getNickName());
        }
    }

    /**
     * 获取礼物数据
     */
    void loadGiftData() {
        if (GiftUtil.getInstance().getShortcutGift() == null) {
            post(BuildConfig.GET_SHORTCUT_GIFT, new FormEncodingBuilderEx().build());
        } else {
            loadShortcutGift();
        }
    }

    /**
     * 查询守护信息
     */
    private void loadContrInfo() {
        if (isLogin() && mStarInfo != null) {
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("uid", getUid())
                    .add("token", getToken())
                    .add("aid", mStarInfo.getUid())
                    .build();
            post(BuildConfig.GET_CONTRIBUTION_INFO, body);
            L.d(TAG + "守护信息UID：", getUid());
            L.d(TAG + "守护信息STARID：", mStarInfo.getUid());
        }
    }

    /**
     * 获取喊话礼物
     */
    void loadChatData() {
        if (GiftUtil.getInstance().getShout() == null) {
            post(BuildConfig.GET_SHOUT_GIFT, new FormEncodingBuilderEx().build());
        } else {
            loadShout();
        }
    }

    boolean mIsMsgReminderOn = false;

    private void switchReminder() {
        if (mIsMsgReminderOn) {
            mMsgReminder.setVisibility(isLastItemVisible() ? View.GONE : View.VISIBLE);
        }
    }

    private boolean isLastItemVisible() {
        if (null == mChatListAdapter || mChatListAdapter.isEmpty()) {
            return true;
        }
        final int lastItemPosition = mChatListAdapter.getCount() - 1;
        final int lastVisiblePosition = mChatListView.getLastVisiblePosition();

        if (lastVisiblePosition >= lastItemPosition - 1) {
            final int childIndex = lastVisiblePosition - mChatListView.getFirstVisiblePosition();
            final int childCount = mChatListView.getChildCount();
            final int index = Math.min(childIndex, childCount - 1);
            final View lastVisibleChild = mChatListView.getChildAt(index);
            if (lastVisibleChild != null) {
                return lastVisibleChild.getBottom() <= mChatListView.getBottom();
            }
        }
        return lastVisiblePosition >= lastItemPosition - 1;
    }

    /**
     * 发送聊天内容
     *
     * @param chatStr chatStr
     */
    private void sendChatContent(String chatStr) {
        sendMqttMsg(ChatData.CHAT_TYPE_CONTENT, chatStr, null, null);
    }

    /**
     * 发送喊话
     *
     * @param chatStr
     * @param giftData
     */
    private void sendGrund(String chatStr, GiftDataModel giftData) {
        sendMqttMsg(ChatData.CHAT_TYPE_GIFT, chatStr, giftData, new GiftNumModel(1));
    }

    /**
     * 快速礼物
     */
    private void sendChatFlower() {
        if (null != mShortCutGiftData) {
            sendMqttMsg(ChatData.CHAT_TYPE_GIFT, "", mShortCutGiftData, new GiftNumModel(1));
        }
    }

    /**
     * 发生mqtt消息
     *
     * @param type
     * @param chatStr
     * @param giftData
     * @param giftNum
     */
    private void sendMqttMsg(int type, String chatStr, GiftDataModel giftData, GiftNumModel giftNum) {
        //消费礼物
        ChatData chatData = new ChatData();
        chatData.setType(type);
        if (isLogin() && getUserInfo() != null) {
            chatData.setUuid(getUid());
            chatData.setNickname(getUserInfo().getNickName());
            chatData.setAvatar(getUserInfo().getPhoto());
        }

        if (ChatData.CHAT_TYPE_VIP_JOIN_IN == type || ChatData.CHAT_TYPE_CONTENT == type) {
            chatData.setBarrageContent(chatStr);
        }

        if (type == ChatData.CHAT_TYPE_GIFT) {
            sendGift(chatStr, giftData, giftNum);
        } else {
            sendMqttChat(chatData);
        }
    }

    /**
     * 发送聊天消息
     *
     * @param chatData
     */
    private void sendMqttChat(ChatData chatData) {
        FormEncodingBuilderEx build = new FormEncodingBuilderEx();
        build.add("uid", getUid());
        build.add("token", getToken());
        build.add("title", mTitle);
        build.add("tip", chatData.getBarrageContent());
        build.add("content", chatData.getBarrageContent());
        if (!StringUtil.isNullorEmpty(getMqttClientId())) {
            build.add("clientId", getMqttClientId());
            build.add("flag", getMqttFlag());
            build.add("key", getMqttKey());
        }
        if (mStarList != null && mStarList.size() > 1) {
            //多个艺人,无法判断守护级别,传1
            build.add("artistIds", getStarIds());
            build.add("grade", (mContributionInfo != null && !StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())) ? mContributionInfo.getGradeLevel() : "1");
        } else {
            //单个艺人,根据守护等级处理,默认为0
            build.add("artistIds", mStarInfo.getUid());
            build.add("grade", (mContributionInfo != null && !StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())) ? mContributionInfo.getGradeLevel() : "0");
        }
        post(BuildConfig.CHAT_SEND_PATH_V2, build.build());
        chatTmp = chatData;
    }

    /**
     * 发送礼物消息
     */
    private void sendGift(String chatStr, GiftDataModel giftData, GiftNumModel giftNum) {
        if (giftData == null || giftNum == null || getStarInfo() == null) {
            return;
        }
        FormEncodingBuilderEx builder = new FormEncodingBuilderEx();
        builder.add("gid", giftData.getGid() + "");
        builder.add("count", giftNum.getGiftNum() + "");
        builder.add("gift", StringUtil.isNullorEmpty(chatStr) ? "1" : "2");
        builder.add("amount", giftNum.getGiftNum() * giftData.getPrice() + "");
        builder.add("buid", getUid());
        builder.add("cuid", getStarInfo().getUid());
        builder.add("token", getToken());
        builder.add("tip", StringUtil.isNullorEmpty(chatStr) ? "送给 " + getStarInfo().getNickName() : chatStr);
        if (!StringUtil.isNullorEmpty(getMqttClientId())) {
            builder.add("clientId", getMqttClientId());
            builder.add("flag", getMqttFlag());
            builder.add("key", getMqttKey());
        }
        post(BuildConfig.PAY_GIFT, builder.build());
    }

    /**
     * 发送守护进场的消息
     */
    public void sendGuardMessage() {
        if (!isLogin() || StringUtil.isNullorEmpty(getMqttClientId()) || getStarInfo() == null
                || !isConnectionMqtt || isSendGuardMsg) {
            //必须登录,并且mqtt连接上,没有发送过守护进场消息
            return;
        }
        FormEncodingBuilderEx builder = new FormEncodingBuilderEx();
        builder.add("uid", getUid());
        builder.add("artistIds", getStarInfo().getUid());
        builder.add("token", getToken());
        builder.add("tip", "");
        builder.add("clientId", getMqttClientId());
        builder.add("flag", getMqttFlag());
        builder.add("key", getMqttKey());
        post(BuildConfig.SEND_GUARD_MSG, builder.build());
        isSendGuardMsg = true;
    }

    private String getStarIds() {
        StringBuilder sb = new StringBuilder();
        if (mStarList != null && mStarList.size() > 0) {
            for (int i = 0; i < mStarList.size(); i++) {
                sb.append(mStarList.get(i).getUid());
                if (i != mStarList.size() - 1) {
                    sb.append(",");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 变更聊天输入框状态
     */
    private void changeChatInput() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (!isShowChatInputView) {
            mGiftIcon.setVisibility(View.GONE);
            //隐藏底部送礼物窗体
            bottomLayout.setVisibility(View.GONE);
            //显示聊天输入框
            inputChatLayout.setVisibility(View.VISIBLE);
            //输入框获得焦点
            inputChatText.requestFocus();
            inputChatText.requestFocusFromTouch();
            //打开软键盘
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            imm.showSoftInputFromInputMethod(inputChatText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            isShowChatInputView = true;
            mEptZone.setVisibility(View.VISIBLE);
            mMessageUtil.changeSpaceTime(true);
        } else {
            mGiftIcon.setVisibility(View.VISIBLE);
            //显示底部送礼物窗体
            bottomLayout.setVisibility(View.VISIBLE);
            //隐藏聊天输入框
            inputChatText.clearFocus();
            inputChatLayout.setVisibility(View.GONE);
            imm.hideSoftInputFromWindow(inputChatText.getWindowToken(), 0);
            isShowChatInputView = false;
            mEptZone.setVisibility(View.GONE);
            mMessageUtil.changeSpaceTime(false);
        }
    }

    long mCurrentHots;

    /**
     * 收到礼物之后增添人气值
     *
     * @param chatData mSendChatData
     */
    private void updateHotValue(ChatData chatData) {
        //收到的礼物必须是当前选择的艺人才增加人气
        if (mStarInfo != null && mStarInfo.getUid() != null
                && mStarInfo.getUid().equals(chatData.getTargetUuid())) {
            try {
                mCurrentHots = Long.valueOf(mCentreFragment.mHotValue.getText().toString());
                long addHots = 0;
                if(chatData.getType() == ChatData.CHAT_TYPE_GIFT){
                    if(mYellGifData != null && chatData.getProductId() == mYellGifData.getGid()){
                        //喊话
                        if(chatData.getGrade() <= 0){
                            addHots = Long.valueOf(mYellGifData.getHots());
                        }
                    }else{
                        addHots = chatData.getHots(mShortCutGiftData) * chatData.getCount();
                    }
                }else if(chatData.getType() == ChatData.CHAT_TYPE_BUY_GUARD){
                    addHots = Long.valueOf(chatData.getHotValue());
                }

                mCurrentHots = mCurrentHots + addHots;
                mCentreFragment.mHotValue.setText("" + mCurrentHots);
            } catch (Exception e) {
                mCentreFragment.mHotValue.setText("" + mCurrentHots);
            }
            if (mChatViewCallback != null) {
                mChatViewCallback.changeStarHotValue(mCurrentHots);
            }
        }
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    /**
     * 获取最新的20条聊天记录
     */
    public void getLastMsg() {
        FormEncodingBuilderEx build = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("flag", getMqttFlag())
                .add("key", getMqttKey())
                .add("artistIds", mStarInfo != null ? mStarInfo.getUid() : "");

        if (isLogin()) {
            UserInfoData data = getUserInfo();
            if (data != null) {
                build.add("img", data.getPhoto());
            }
        }

        if (mContributionInfo != null && !StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())) {
            build.add("grade", mContributionInfo.getGradeLevel());
        } else {
            build.add("grade", "0");
        }
        Map<String, String> body = build.build();
        post(BuildConfig.CHAT_GET_LAST_MSG_PATH, body);
    }

    /**
     * 请求是否有直播开启
     */
    public void getIsLiveOpen() {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("token", getToken())
                .add("aid", mStarInfo.getUid())
                .build();
        post(BuildConfig.URL_LIVE_IS_OPEN, body);
    }

    @Override
    public void arrivedMessage(MqttResponseData data) {
        try {
            //解析聊天数据
            ChatData chatData = JSON.parseObject(data.getDatas(), ChatData.class);
            if (chatData != null) {
                if (chatData.getType() == ChatData.CHAT_TYPE_LIVE_MESSAGE) {//直播消息
                    mHandler.sendEmptyMessage(LIVE_OPEN_MSG);
                } else {
                    if (null != mChatViewCallback && chatData.getType() != 0) {
                        mChatViewCallback.changeOnline(data.getOnline() + "");
                    }
                    showChatData(chatData, true);
                }
            }
            if (!mIsMsgReminderOn) {
                mIsMsgReminderOn = true;
            }
        } catch (Exception e) {
            L.d("MQTT ERROR", data.getDatas());
            e.printStackTrace();
        }
    }

    /**
     * 显示直播消息
     */
    LiveRemindDialog mLiveReindDialog;

    private void showLiveMessageDialog() {
        if (mStarInfo != null) {
            if (mLiveReindDialog == null) {
                String imageUrl = mStarInfo.getPhoto();
                String nickName = mStarInfo.getNickName();
                String uId = mStarInfo.getUid();
                mLiveReindDialog = new LiveRemindDialog(getContext(), uId, nickName, imageUrl);
            }
            if (!mLiveReindDialog.isShowing()) {
                mLiveReindDialog.show();
            }
        }

    }

    /**
     * 显示聊天内容
     *
     * @param chatData
     * @param showStarMsg
     */
    private void showChatData(ChatData chatData, boolean showStarMsg) {
        ChatDataModel chatModle;
        if (chatData.getType() == ChatData.CHAT_TYPE_GIFT) {
            if (mYellGifData != null && mYellGifData.getGid() == chatData.getProductId()) {//喊话
                Message msg = mHandler.obtainMessage(CHAT_SEND_MSG, chatData);
                mHandler.sendMessage(msg);
            } else {
                StarModel model = getSelectStarByChatMessage(chatData.getTargetUuid());
                if(model != null){
                    GiftShowViewDataModel dataModel = chatData.getGiftShowDataModel(model);
                    if (dataModel == null) {
                        dataModel = chatData.getGiftShowDataModel(mShortCutGiftData, model);
                    }
                    Message msg = mHandler.obtainMessage(CHAT_SEND_GIFT, dataModel);//礼物
                    mHandler.sendMessage(msg);
                    chatModle = chatData.toChatModle(mShortCutGiftData, model.getNickName());
                    if(!StringUtil.isNullorEmpty(chatModle.giftName) && !StringUtil.isNullorEmpty(chatModle.giftPhoto))
                    {
                        //只有匹配到礼物才显示
                        sendMsg(chatData, showStarMsg, chatModle);
                    }
                }

            }
            //刷新人气值
            Message msg = mHandler.obtainMessage(CHAT_UPDATE_HOT_VALUE, chatData);
            mHandler.sendMessage(msg);
        } else if (ChatData.CHAT_TYPE_VIP_JOIN_IN == chatData.getType()) {
            if (chatData.getGrade() >= 1) {
                chatModle = chatData.toChatModle();
                sendMsg(chatData, showStarMsg, chatModle);
            }
        } else if (ChatData.CHAT_TYPE_CONTENT == chatData.getType() || ChatData.CHAT_TYPE_DANMO == chatData.getType()) {
            chatModle = chatData.toChatModle();
            if (ChatData.CHAT_TYPE_CONTENT == chatData.getType() && isLogin() && getUid().equals(chatData.getUuid())) {
                //收到自己的消息不做处理
            } else {
                sendMsg(chatData, showStarMsg, chatModle);
            }

        } else if (ChatData.CHAT_TYPE_STAR_CHANGE == chatData.getType()) {
            Message msg = mHandler.obtainMessage(CHAT_SEND_MSG, chatData);
            mHandler.sendMessage(msg);
        } else if(ChatData.CHAT_TYPE_BUY_GUARD == chatData.getType())
        {
            StarModel model = getSelectStarByChatMessage(chatData.getUuid());
            if(model != null){
                chatModle = chatData.toCharModelByGrund(model.getNickName());
                sendMsg(chatData, showStarMsg, chatModle);

                //刷新人气值
                Message msg = mHandler.obtainMessage(CHAT_UPDATE_HOT_VALUE, chatData);
                mHandler.sendMessage(msg);
            }
        }
    }

    /**
     * 获取送礼目标艺人
     * @param uuid
     * @return
     */
    private StarModel getSelectStarByChatMessage(String uuid){
        StarModel star = null;
        if (null != mStarList) {
            for (StarModel md : mStarList) {
                if (md.getUid().equals(uuid)) {
                    star = md;
                    break;
                }
            }
        }
        if (star == null && mStarInfo != null && mStarInfo.getUid().equals(uuid)) {
            star = mStarInfo;
        }
        return star;
    }

    private void sendMsg(ChatData chatData, boolean showStarMsg, ChatDataModel chatModle) {
        if (chatModle != null) {
            Message msg = mHandler.obtainMessage(CHAT_NNOTIFY, chatModle);//聊天室消息
            mHandler.sendMessage(msg);
            if (ChatData.CHAT_TYPE_DANMO == chatData.getType() || ChatData.CHAT_TYPE_CONTENT == chatData.getType()) {
                if (showStarMsg) {
                    Message starMsg = mHandler.obtainMessage(CHAT_STAR_MSG, chatModle);//主播回复
                    mHandler.sendMessage(starMsg);
                }
                Message msgd = mHandler.obtainMessage(CHAT_SEND_MSG, chatData);
                mHandler.sendMessage(msgd);
            }
        }
    }

    boolean isConnectionMqtt = false;//是否连接mqtt
    boolean isSendGuardMsg = false;//是否发送过守护进场信息

    @Override
    public void connectionSuccess() {
        isConnectionMqtt = true;
        sendGuardMessage();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadGiftData();
        loadContrInfo();

        mHandler.removeMessages(CHAT_SEND_MSG);
        if(mIsOpenConnectionMqtt)
        {
            connectionMqtt();
        }
    }

    private void connectionMqtt(){
        //重新连接mqtt
        if(!getMqtt().isConnection()
                || (!StringUtil.isNullorEmpty(mFlag) && !StringUtil.isNullorEmpty(mKey)
                && !mFlag.equals(getMqtt().getFlag()) && !mKey.equals(getMqtt().getFlag()))){
            getMqtt().startMqttService(mFlag, mKey, this);
        }
    }

    @Override
    public void onPause() {
        mIsOpenConnectionMqtt = true;
        super.onPause();
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        super.onSucceed(url, resultModel);
        if (url != null) {
            if (BuildConfig.GET_SHORTCUT_GIFT.equals(url)) {
                GiftDataModel gift = (GiftDataModel) resultModel.getDataModel();
                GiftUtil.getInstance().setShortcutGift(gift);
                loadShortcutGift();
            } else if (BuildConfig.GET_SHOUT_GIFT.equals(url)) {
                GiftUtil.getInstance().setShout((GiftDataModel) resultModel.getDataModel());
                loadShout();
            } else if (BuildConfig.PAY_GIFT.equals(url)) {
                if (mChatViewCallback != null && giftAnimData != null) {
                    mChatViewCallback.startAnim(giftAnimData.photo, giftAnimData.hots, giftAnimData.formX, giftAnimData.formY);
                    giftAnimData = null;
                }
            } else if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
                //守护信息
                mContributionInfo = JSON.parseObject(resultModel.getData(), ContributionInfoData.class);
                if (isYell && inputChatText != null && mContributionInfo != null && !ContributionInfoData.GRADE_LEVEL_NO.equals(mContributionInfo.getGradeName())) {
                    inputChatText.setHint(getString(R.string.live_send_msg_vip));
                }
            } else if (BuildConfig.CHAT_GET_LAST_MSG_PATH.equals(url)) {
                List<ChatDataModel> chatList = (List<ChatDataModel>) resultModel.getDataModel();
                Message msg = mHandler.obtainMessage(CHAT_LAST_MSG, chatList);
                mHandler.sendMessage(msg);
            } else if (BuildConfig.SEND_GUARD_MSG.equals(url)) {//进场成功
            } else if (BuildConfig.URL_LIVE_IS_OPEN.equals(url)) {//直播状态
                String data = resultModel.getData();
                if (!StringUtil.isNullorEmpty(data) && data.contains("online")) {//在直播
                    showLiveMessageDialog();
                }
            }else if(BuildConfig.CHAT_SEND_PATH_V2.equals(url)){
                //自己发送的消息显示
                //本地显示自己的消息需重新处理role与grade
                if(chatTmp != null)
                {
                    if (mContributionInfo != null && !StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())) {
                        chatTmp.setGrade(Integer.parseInt(mContributionInfo.getGradeLevel()));
                    } else {
                        chatTmp.setGrade(0);
                    }
                    if (isLogin() && getUserInfo() != null) {
                        chatTmp.setRole(getUserInfo().getRole());
                    } else {
                        chatTmp.setRole(RoleUtil.ROLE_PT);
                    }

                    sendMsg(chatTmp, true, chatTmp.toChatModle());
                }
                chatTmp = null;
            }
        }
    }

    private void loadShortcutGift() {
        mShortCutGiftData = GiftUtil.getInstance().getShortcutGift();
        updateShortCutGiftView();
    }

    private void loadShout() {
        mYellGifData = GiftUtil.getInstance().getShout();
        updateSendChatEditTextView();
        sendChatBtn.setEnabled(true);
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (url.contains(BuildConfig.CHAT_ONLINE_PATH)) {
            MqttResponseData responseData = JSON.parseObject(resultModel.getData(), MqttResponseData.class);
            if (null != mChatViewCallback) {
                mChatViewCallback.changeOnline(responseData.getOnline() + "");
            }
        }else if (url.contains(BuildConfig.GET_SHOUT_GIFT) || url.contains(BuildConfig.GET_SHORTCUT_GIFT)) {
            return JSON.parseObject(resultModel.getData(), GiftDataModel.class);
        } else if (url.contains(BuildConfig.CHAT_GET_LAST_MSG_PATH)) {
            MqttLastMsgData data = JSON.parseObject(resultModel.getData(), MqttLastMsgData.class);
            if (null != mChatViewCallback) {
                mChatViewCallback.changeOnline(data.getOnline() + "");
            }
            List<ChatDataModel> chatList = new ArrayList<>();
            if (null != data && null != data.getLastMsg() && data.getLastMsg().size() > 0) {
                for (int i = 0; i < data.getLastMsg().size(); i++) {
                    ChatData da = JSON.parseObject(data.getLastMsg().get(i), ChatData.class);
                    if (null != da) {
                        ChatDataModel chatModle = da.toChatModle();
                        chatList.add(chatModle);
                    }
                }
            }
            return chatList;
        }
        return super.asyncExecute(url, resultModel);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if (BuildConfig.PAY_GIFT.equals(url)) {
            if ("2201".equals(resultModel.getCode()) || resultModel.getMsg().startsWith("剩余金币不足")) {
                if (!mConfirmDialog.isShowing()) {
                    mConfirmDialog.show();
                }
            }
            giftAnimData = null;
        }else if (BuildConfig.URL_LIVE_IS_OPEN.equals(url)) {
            //直播询问报错不弹出提示
        }else if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
            //守护信息
            mContributionInfo = null;
        }
        else if (!"200".equals(resultModel.getCode()) && !"10".equals(resultModel.getCode())) {//敏感信息不提示
            if(BuildConfig.CHAT_SEND_PATH_V2.equals(url)){
                chatTmp = null;
            }
            Toast.makeText(getContext(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
        super.onFailure(url, resultModel);

    }

    @Override
    public void onError(String url, Exception e) {
        if (BuildConfig.PAY_GIFT.equals(url)) {
            giftAnimData = null;
        }else if(BuildConfig.CHAT_SEND_PATH_V2.equals(url)){
            chatTmp = null;
        }
        super.onError(url, e);
    }

    public void setStarList(List<StarModel> mStarList) {
        this.mStarList = mStarList;
    }

    /**
     * 获取艺人信息对象
     *
     * @return StarModel
     */
    public StarModel getStarInfo() {
        return mStarInfo;
    }

    public void updateHotValue(String hotValue) {
        mCentreFragment.updateHotValue(hotValue);
    }

    public void setChatViewCallback(ChatViewCallback call) {
        mChatViewCallback = call;
    }

    /**
     * 设置videoFragment的回调函数
     *
     * @param changedCallback changedCallback
     */
    public void setVideoViewListener(StarLiveDetailCentreFragment.ICenterViewCallback changedCallback) {
        if (mCentreFragment != null) {
            mCentreFragment.setVideoViewListener(changedCallback);
        }
    }

    public boolean onBackPressed() {
        if (isShowChatInputView) {
            changeChatInput();
            return true;
        }
        return mCentreFragment.onBackPressed();
    }

    @Override
    public void onDestroy() {
        mChatViewCallback = null;
        super.onDestroy();
    }

    private Thread thread = new Thread() {

        @Override
        public void run() {
            super.run();
            while (true) {
                for (int i = 0; i < 1000; i++) {
                    MqttResponseData data = new MqttResponseData();
                    data.setDatas("{\"barrageContent\":\"哈哈" + i + "\",\"nickName\":\"简单点好。\",\"uuid\":\"a874cae07a0fe34cd395728e95351de7\",\"avatar\":\"http://userpic.cdn.max.mgtv.com/2016011817111468609_mgtv.jpg@1e_1c_0o_1l_150h_150w\",\"type\":1}");
                    data.setOnline(2);
                    data.setTotal(1);
                    arrivedMessage(data);
                }
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    public void notifyList() {
        if (mChatListAdapter != null) {
            mChatListAdapter.notifyDataSetChanged();
            switchReminder();
        }
    }

    public void screenOrietantionChanged(boolean island) {
        if (island) {
            if (isShowChatInputView) {
                changeChatInput();
            }
            mAnimOtherView.setVisibility(View.GONE);
            mCentreFragment.onBackPressed();
            int topMargin = getContext().getResources().getDimensionPixelOffset(R.dimen.height_56dp);
            RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) mGifyShowView.getLayoutParams();
            ps.topMargin = topMargin;
            mGifyShowView.setLayoutParams(ps);
            mGifyShowView.setGravity(Gravity.LEFT);
            mGiftShowView.setIsAnimLeft(true);
        }else
        {
            mAnimOtherView.setVisibility(View.VISIBLE);
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
            RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) mGifyShowView.getLayoutParams();
            int topMargin = getContext().getResources().getDimensionPixelOffset(R.dimen.height_56dp);
            ps.topMargin = topMargin + (int) (width * 0.75);
            mGifyShowView.setLayoutParams(ps);
            mGifyShowView.setGravity(Gravity.RIGHT);
            mGiftShowView.setIsAnimLeft(false);
        }
    }

    private class GiftAnimData {
        public String photo;
        public String hots;
        public int formX;
        public int formY;
    }
}

